import os
import cv2
import tempfile

def main():
    with open( "/home/jh/working_data/anti-spoofing/Oulu_NPU/tmp/protocols/p1_Test.txt" \
            , "r" ) as fo:
        lines = fo.readlines()

        for idx, line in enumerate( lines):
            if idx % 200 == 0 :
                print( "processing %d / %d" % ( idx, len(lines) ))
            line_split = line.strip().split( " " )

            img = cv2.imread( line_split[0] )
            height, width, _ = img.shape

            lx = int( line_split[1] )
            ly = int( line_split[2] )
            rx = int( line_split[3] )
            ry = int( line_split[4] )

            cy = ( ly + ry ) // 2
            l = lx - ( rx - lx ) // 2
            r = rx + ( rx - lx ) // 2
            u = cy - ( rx - lx )
            d = cy + 2 * ( rx - lx )

            merged_l = max( 0 , l )
            merged_u = max( 0 , u )
            merged_r = min( width -1 , r )
            merged_d = min( height-1 , d )

            if line_split[-1] == "1":
                img_name = tempfile.mktemp( dir = "./pos" , suffix = ".jpg" )
            else:
                img_name = tempfile.mktemp( dir = "./neg" , suffix = ".jpg" )

            cv2.imwrite( img_name ,\
                    img[ merged_u:merged_d , merged_l:merged_r , : ] )

def main1():
    with open( "/home/jh/working_data/anti-spoofing/HomeMadeData2/100_printed/test_resized/test_file.txt" \
            , "r" ) as fo:
        lines = fo.readlines()

        for idx, line in enumerate( lines):
            if idx % 200 == 0 :
                print( "processing %d / %d" % ( idx, len(lines) ))
            line_split = line.strip().split( " " )

            img = cv2.imread( line_split[0] )
            height, width, _ = img.shape

            l = int( line_split[1] )
            u = int( line_split[2] )
            r = int( line_split[3] )
            d = int( line_split[4] )

            merged_l = max( 0 , l )
            merged_u = max( 0 , u )
            merged_r = min( width -1 , r )
            merged_d = min( height-1 , d )

            if line_split[-1] == "1":
                img_name = tempfile.mktemp( dir = "./neg1" , suffix = ".jpg" )
            else:
                img_name = tempfile.mktemp( dir = "./pos1" , suffix = ".jpg" )

            cv2.imwrite( img_name ,\
                    img[ merged_u:merged_d , merged_l:merged_r , : ] )
if __name__ == "__main__":
    main1()
